package web

import (
	"github.com/aphasia51/website/internal/domain"
	"github.com/aphasia51/website/internal/service"
	"github.com/gin-gonic/gin"
	"net/http"
)

type ChemicalHandler struct {
	svc *service.ChemicalService
}

func NewChemicalHandler(svc *service.ChemicalService) *ChemicalHandler {
	return &ChemicalHandler{
		svc: svc,
	}
}

func (c *ChemicalHandler) RegistryRoutes(server *gin.Engine) {
	cg := server.Group("/chemical")
	cg.POST("/query", c.Query)
	cg.POST("/select", c.Select) // chemicals select
}

func (c *ChemicalHandler) Query(ctx *gin.Context) {
	type ChemicalReq struct {
		Chemical            string `json:"chemical"`
		SimilarChemical     string `json:"similarChemical"`
		IfHazardousChemical string `json:"ifHazardousChemical"`
	}
	var req ChemicalReq
	if err := ctx.Bind(&req); err != nil {
		panic(err)
	}

	chemicals, err := c.svc.Query(ctx, domain.Chemical{
		Chemical:            req.Chemical,
		SimilarChemical:     req.SimilarChemical,
		IfHazardousChemical: req.IfHazardousChemical,
	})

	if err != nil {
		ctx.String(http.StatusOK, "query error")
		return
	}

	ctx.JSON(http.StatusOK, chemicals)
}

func (c *ChemicalHandler) Select(ctx *gin.Context) {
	chemicals, err := c.svc.Select(ctx)

	if err != nil {
		ctx.String(http.StatusOK, "query error")
		return
	}

	ctx.JSON(http.StatusOK, chemicals)
}
